use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, Read};
use std::path::PathBuf;
use std::{env, io};

pub fn converter(input: &str, tp: &str) -> String {
    let (s2t_dict, t2s_dict) = init_dict();
    match tp {
        "s2t" => {
            do_converter(input, s2t_dict)
        }
        "t2s" => {
            do_converter(input, t2s_dict)
        }
        _ => {
            String::new()
        }
    }
}

fn do_converter(input: &str, dict: HashMap<String, String>) -> String {
    let mut res = String::new();
    let mut i = 0;
    let mut j = 0;
    let chars: Vec<_> = input.chars().collect();
    while i < chars.len() {
        j = chars.len();
        while i < j {
            let s: &String = &chars[i..j].iter().collect();
            if dict.contains_key(s) {
                break;
            }
            j -= 1;
        }
        if i == j {
            res += &chars[i].to_string();
            i += 1;
        } else {
            let s: &String = &chars[i..j].iter().collect();
            res += &dict[s];
            i = j;
        }
    }
    res
}

fn init_dict() -> (HashMap<String, String>, HashMap<String, String>) {
    let workspace = PathBuf::from(find_workspace_root().unwrap());
    let file_path = "topic1/solutiont6/S2T.txt";
    let path = workspace.join(file_path);
    let file = File::open(path).unwrap();
    let reader = io::BufReader::new(file);

    let mut s2t_dict = HashMap::new();
    let mut t2s_dict = HashMap::new();
    for line in reader.lines() {
        let line = line.unwrap(); // 获取每一行内容
        let parts: Vec<&str> = line.split_whitespace().collect(); // 按空格分割

        s2t_dict.insert(parts[0].to_string(), parts[1].to_string());
        t2s_dict.insert(parts[1].to_string(), parts[0].to_string());
    }
    (s2t_dict, t2s_dict)
}


fn find_workspace_root() -> Option<String> {
    let mut current_dir = env::current_dir().ok()?;
    let cargo_toml_path = current_dir.join("Cargo.toml");
    if cargo_toml_path.is_file() {
        let mut file = File::open(cargo_toml_path).unwrap();
        let mut json = String::new();
        file.read_to_string(&mut json).unwrap();
        if json.contains("[workspace]") {
            return Some(current_dir.to_str().unwrap().to_string());
        }
    }

    while current_dir.parent().is_some() {
        current_dir = current_dir.parent()?.to_path_buf();
        let cargo_toml_path = current_dir.join("Cargo.toml");
        if cargo_toml_path.is_file() {
            let mut file = File::open(cargo_toml_path).unwrap();
            let mut json = String::new();
            file.read_to_string(&mut json).unwrap();
            if json.contains("[workspace]") {
                return Some(current_dir.to_str().unwrap().to_string());
            }
        }
    }

    None
}